import { useMemo, useState, useCallback } from 'react';
import { View } from '@tarojs/components';
import i18n from 'i18n-js';
import { observer } from 'mobx-react';
import Taro from '@tarojs/taro';
import { GStyleSheet } from '@/utils/DarkMode';
import { useDeviceListStore, useDeviceShare } from '@/hooks';
import FlexScrollView from '@/components/FlexScrollView';
import { isSameDevice } from '@/utils';
import deviceShareModel from '@/models/deviceShare';
import { cancelDeviceShare } from '@/services/share';
import Toast from '@/utils/Toast';
import DeviceItem from './components/DeviceItem';
import { ISelDevice, noRepeatAddItemToArray, deleteItemFromArray } from './models';
import BottomButtonView from './container/BottomButtonView';
import StopShareAlert from './container/StopShareAlert';
import manageIcon from '../images/manage.png';
import CheckBox from '@/components/CheckBox';

const dstyles = GStyleSheet.create({
  content: {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
  },
  checkBox: {
    height: 18,
    width: 18,
    borderColor: '#A4A4A4',
  },
});

function MyShareDeviceList() {
  const styles = dstyles.useDynamicStyle();
  const [isEdit, setIsEdit] = useState(false);
  const [stopAlertShow, setStopAlertShow] = useState(false);
  const [sharedDeviceSelectList, setSharedDeviceSelectList] = useState<ISelDevice[]>([]);
  const { list } = useDeviceShare();
  const { data } = useDeviceListStore();
  const deviceList: ISelDevice[] = useMemo(() => {
    const arr: ISelDevice[] = [];
    list.forEach(sDevice => {
      const d = data.find(i => isSameDevice(i, sDevice));
      if (d) {
        arr.push({
          ...d,
          count: sDevice.count,
          isSelected: sharedDeviceSelectList.findIndex(i => isSameDevice(i, d)) > -1,
        });
      }
    });
    return arr;
  }, [data, list, sharedDeviceSelectList]);

  console.log('MyShareDeviceList更新', deviceList);

  const isAllCheck = useMemo(() => {
    const currentSelect = sharedDeviceSelectList
      .sort()
      .map(item => item.deviceId)
      .join('');
    const allDevice = deviceList
      .sort()
      .map(item => item.deviceId)
      .join('');
    return currentSelect === allDevice;
  }, [sharedDeviceSelectList, deviceList]);

  const onDeviceItemPress = useCallback(
    ({ device }: { device: ISelDevice }) => {
      if (isEdit) {
        const targetSel = !device.isSelected;
        if (targetSel) {
          noRepeatAddItemToArray({ list: sharedDeviceSelectList, item: device, isSame: isSameDevice });
        } else {
          deleteItemFromArray({ list: sharedDeviceSelectList, item: device, isSame: isSameDevice });
        }
        setSharedDeviceSelectList([...sharedDeviceSelectList]);
      } else {
        Taro.navigateTo({
          url: `/pages/share/users/index?pk=${device.productKey}&mac=${device.mac}`,
        });
      }
    },
    [isEdit, sharedDeviceSelectList]
  );

  const closeStopAlert = useCallback(() => {
    setStopAlertShow(false);
  }, []);

  const showStopAlert = useCallback(() => {
    setStopAlertShow(true);
  }, []);

  const deleteClick = useCallback(async () => {
    closeStopAlert();
    if (sharedDeviceSelectList && sharedDeviceSelectList.length > 0) {
      Toast.loading('');
      const res = await cancelDeviceShare(sharedDeviceSelectList);
      if (res.success) {
        await deviceShareModel.fetchList();
      }
      Toast.hideLoading();
    }
    setIsEdit(false);
    setSharedDeviceSelectList([]);
  }, [sharedDeviceSelectList, closeStopAlert]);

  const goToAddShare = useCallback(async () => {
    if (sharedDeviceSelectList && sharedDeviceSelectList.length > 0) {
      deviceShareModel.setSelectedDevices(sharedDeviceSelectList);
      const res = await deviceShareModel.createDeviceShareRecord();
      if (!res.success || !res.data) {
        return;
      }
      Taro.navigateTo({
        url: `/pages/share/modes/index?shareId=${res.data}`,
      });
    }
    setIsEdit(false);
    setSharedDeviceSelectList([]);
  }, [sharedDeviceSelectList]);

  const buttonData = useMemo(() => {
    return isEdit
      ? [
          { title: i18n.t('STOP_SHARE'), onClick: showStopAlert, color: 'danger', variant: 'outlined' },
          { title: i18n.t('SHARE'), onClick: goToAddShare },
        ]
      : [{ title: i18n.t('MANAGE'), onClick: () => setIsEdit(true), icon: manageIcon }];
  }, [isEdit, showStopAlert, goToAddShare]);

  const toggleSelect = useCallback(() => {
    if (isAllCheck) {
      setSharedDeviceSelectList([]);
    } else {
      setSharedDeviceSelectList([...deviceList]);
    }
  }, [isAllCheck, deviceList]);
  return (
    <View style={styles.content}>
      <View style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
        {isEdit ? (
          <View style={{ justifyContent: 'flex-end', display: 'flex', padding: '10PX 16PX 0PX 20PX' }}>
            <CheckBox style={styles.checkBox} checked={isAllCheck} onPress={toggleSelect}></CheckBox>
          </View>
        ) : null}
        <FlexScrollView id='MyShareDeviceList'>
          {deviceList.map(item => (
            <DeviceItem
              key={item.deviceId}
              isSelected={item.isSelected}
              showSel={isEdit}
              device={item}
              count={item.count}
              onPress={onDeviceItemPress}
            />
          ))}
        </FlexScrollView>
      </View>
      <BottomButtonView data={buttonData} />
      <StopShareAlert visible={stopAlertShow} onClose={closeStopAlert} onConfirm={deleteClick} />
    </View>
  );
}

export default observer(MyShareDeviceList);
